<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-09 15:45:37
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description:检验单 返工刷卡 会自动删除检验单
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Repositories\CustomerStorageStyleRepository;
use App\Repositories\OpenCardDetailsRepository;
use App\Repositories\ProProcessesPassRepository;
use App\Repositories\ProProcessesInspectRepository;

use Illuminate\Support\Facades\DB;

/**
 * @property ProProcessesInspectRepository $repository 
 * @author sunkaiyuan
 */
class InspectService extends Service
    {
    public function __construct(ProProcessesInspectRepository $repository)
        {
        $this->repository = $repository;
        }
    protected function save()
        {
        $data = request()->toArray();
        return $this->repository->autosave($data);
        }

    protected function delete($ids = null)
        {
        return $this->repository->whereIn("id", $ids ?? $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 0) {
                fail("操作失败！单据状态{$v->status->name}");
                }
            return ProProcessesPassRepository::run('deletePass', [$v->process_pass_id]);
            });
        }
    protected function audit()
        {
        $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 0) {
                fail("已入库禁止入库！");
                }

            if ($v->state == 1) {
                $v->order->first_check_status_id = 1;
                $v->order->save();
                }
            else if ($v->state == 0) {
                $this->repository->stockIn($v);
                }

            auditSave($v);
            });
        }

    protected function noaudit()
        {
        $this->repository->whereIn("id", $this->getRequestIds())->get()->filter(function ($v)
            {

            if ($v->status_id != 1) {
                fail("未入库禁止反审！");
                }

            if ($v->state == 1) {
                $v->order->first_check_status_id = 0;
                $v->order->save();
                }
            else if ($v->state == 0) {
                $this->repository->noStockIn($v);
                }
            auditSave($v, false);
            });
        }
    public function info()
        {
        $request = request();
        $code    = $request->code;
        if (substr($request->code, 0, 2) != 'IP') {
            $open_card_m = OpenCardDetailsRepository::whereCode($request->code)->first();
            if ($open_card_m) {
                if ($open_card_m->inspect) {
                    $code = $open_card_m->inspect->code;
                    }
                else {
                    $code = $open_card_m->order->inspect?->code;
                    }
                if ($code == null) {
                    fail("此单无需检验！");
                    }
                }
            else {
                fail("不存在此流转卡");
                }
            }

        $order = $this->repository->whereCode($code)->with(['pack' => ['scrap'], 'order' => ['main'], 'location'])->getOne()->toArray();

        if ($order['state'] != 1)
            $order['style_id'] = CustomerStorageStyleRepository::where("fect_quantity", 0)->whereOrder_id($order['order_id'])->value("id");
        else
            $order['style_id'] = 0;
        return $order;
        }
    public function list()
        {
        // 临时兼容选样单号
        $request = request();
        $filter  = $request->input('filter', []);

        foreach ($filter as $key => $condition) {
            if (
                isset($condition['material.name']) &&
                isset($condition['material.name']['value']) &&
                (strpos($condition['material.name']['value'], 'L') === 0 || strpos($condition['material.name']['value'], 'l') === 0)
            ) {
                // 添加order.sample_code条件
                $filter[$key]['order.sample_code'] = [
                    'type'  => 'lk',
                    'value' => $condition['material.name']['value']
                ];

                // 移除material.name条件
                unset($filter[$key]['material.name']);

                break;
                }
            }

        // 将修改后的filter设置回request
        $request->merge(['filter' => $filter]);

        // 这行保持不变
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }

    public function printReport()
        {
        $list = $this->repository->relation()->whereIn("id", $this->getRequestIds())->get();
        $res  = [];
        $zcd  = [];

        if (request("name") == '指标标签') {
            $list->filter(function ($data) use (&$res, &$zcd)
                {
                $data->order;
                $data->order->strip_index;
                $data->order->washed_index;
                $data->company;
                foreach ($data->toArray() as $k => $potitem) {
                    $v['talbe_' . $k] = $potitem;
                    }
                $res[] = $v;
                });
            }
        else {

            $list->filter(function ($data) use (&$res, &$zcd)
                {
                $row                     = [];
                $row['faultle_quantity'] = $data->quantity;
                $row['title']            = $data->state == 1 ? "初检" : "终检";
                $row['code']             = $data->code;
                $row['dyelot']           = $data->dyelot;
                $row['cust_order']       = $data->cust_order;
                $row['color_name']       = $data->color_name;
                $row['material_name']    = $data->material->name . (isEmpty($data->custno) ? "" : "({$data->custno})");
                $row['customer_name']    = $data->company->code;
                $row['craft_name']       = $data->order?->craft_remark;
                $data->pack()->orderBy("reel")->get()->filter(function ($v) use (&$res, &$zcd, &$row)
                    {
                    $row['reel']           = $v->reel;
                    $row['checkNum']       = $v->quantity;
                    $row['check_weight']   = $v->check_weight;
                    $row['grade']          = $v->grade;
                    $row['material_width'] = $v->width == 0 ? "" : $v->width;
                    $row['checker']        = $v->swipor?->name;
                    $defrow                = $row;
                    $v->scrap->filter(function ($vv, $k) use (&$res, &$zcd, &$defrow)
                        {
                        $defrow['position' . $k] = (int) $vv->position;
                        $defrow['defect' . $k]   = $vv->defect->defectID;
                        $defrow['point' . $k]    = $vv->point;

                        $zcd[$vv->defect->defectID] = $vv->defect->defectID . ":" . $vv->defect->defectName . " " . $vv->defect->defectEnName;
                        });
                    $res[] = $defrow;
                    });


                // 

                });
            foreach ($res as $k => $v) {
                $res[$k]['zcd'] = implode(";", $zcd);
                }
            }

        return createReport($res);
        }
    }